package com.king.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.king.common.lang.Result;
import com.king.entity.Blog;
import com.king.service.BlogService;
import com.king.util.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author KING
 * @since 2020-08-16
 */
@RestController
public class BlogController {
    @Autowired
    BlogService blogService;

    @GetMapping("/blogs")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage){
        Page page = new Page(currentPage,5);
        IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));
        return Result.success(pageData);
    }

    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable("id") Long id){
        Blog blog = blogService.getById(id);
        Assert.notNull(blog,"该博客已被删除！");
        return Result.success(blog);
    }

    @RequiresAuthentication
    @PostMapping("/blog/edit")
    public Result edit(@Validated @RequestBody Blog blog){
        Blog tmp = new Blog();
        if(StringUtils.isEmpty(blog.getId())){//新增
            tmp.setUserId(ShiroUtils.getAccountProfile().getId());
            tmp.setCreated(LocalDateTime.now());
            tmp.setStatus(0);
        }else{//编辑
            tmp = blogService.getById(blog.getId());
            Assert.isTrue(tmp.getUserId().equals(ShiroUtils.getAccountProfile().getId()),"没有权限编辑");
        }

        BeanUtils.copyProperties(blog,tmp,"id","userId","created","status");

        blogService.saveOrUpdate(tmp);
        return Result.success(null);
    }

    @RequiresAuthentication
    @PostMapping("/blog/del")
    public Result delete(@RequestBody Blog blog){
        Assert.notNull(blog.getId(),"博客ID不能为空");
        blogService.removeById(blog.getId());
        return Result.success(null);
    }
}
